package org.wolfengi.handler.util;

import org.wolfengi.handler.common.Constants;

import java.sql.*;

/**
 * @Author: wolfengi
 * @Description: ${TODO}
 * @Date: Created in 11:36 2020/5/19
 * @Modified By:
 */
public class JDBCUtils {
    /**
     * 通过静态代码块，初始化数据库连接配置数据，并且注册数据库驱动
     */
    static {
        try {
            Class.forName(Constants.DIRVERCLASS);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            throw new RuntimeException("获取数据库连接异常，请检查配置数据");
        }
    }

    /**
     * 获取数据库连接对象
     *
     * @return
     */
    public static Connection getConnection() {
        Connection con = null;
        try {
            con = DriverManager.getConnection(Constants.URL, Constants.USERNAME, Constants.PASSWORD);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("获取数据库连接异常，请检查配置数据");
        }
        return con;
    }

    /**
     * 关闭JDBC相关资源
     *
     * @param con
     * @param sta
     * @param rs
     */
    public static void close(Connection con, Statement sta, ResultSet rs) {
        try {
            if (con != null) {
                con.close();
            }
            if (sta != null) {
                sta.close();
            }
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void truncateTable(String tableName) throws SQLException {
        //注册驱动    使用驱动连接数据库
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            con = JDBCUtils.getConnection();

            String sql = "truncate " + tableName;
            stmt = con.prepareStatement(sql);
            boolean result = stmt.execute(sql);// 返回值代表收到影响的行数
//                if (result) {
//                    System.out.println("删除成功");
//                } else {
//                    System.out.println("删除失败");
//                }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.close(con, stmt, rs);
        }
    }

}
